package com.example.algorithm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 设计一个简易数据库系统
 *
 * @author
 * @DATE 2024/7/7
 **/
public class DesignDatabase {

    public static void main(String[] args) {

    }

    // 存放tableId和对应的值
    Map<Integer, List<int[]>> tables = new HashMap<>();
    // 存放tableId和主键
    Map<Integer, String> tableKey = new HashMap<>();
    // 存放主键对应的值，用于校验是否有冲突
    Set<String> id = new HashSet<>();

    // 创建
    private void create(int tableId, int colNum, String keys) {
        if (!tables.containsKey(tableId)) {
            tables.put(tableId, new ArrayList<>());
            tableKey.put(tableId, keys);
        }
    }

    // 插入
    private void inset(int tableId, int[] values) {
        String keys = tableKey.get(tableId);
        char[] charArray = keys.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (char c : charArray) {
            sb.append(values[c - 'a']).append(";");
        }
        sb.append(tableId);
        if (!id.contains(sb.toString())) {
            id.add(sb.toString());
            tables.get(tableId).add(values);
        }
    }

    // 查询
    private List<int[]> select(int tableId, String[] conditions) {
        List<int[]> datas = tables.get(tableId);
        Map<Character, Integer> map = new HashMap<>();
        for (String condition : conditions) {
            String[] split = condition.split("=");
            map.put(split[0].charAt(0), Integer.valueOf(split[1]));
        }
        List<int[]> result = new ArrayList<>();
        for (int[] data : datas) {
            boolean match = true;
            for (Character c : map.keySet()) {
                int index = c - 'a';
                if (data[index] != map.get(c)) {
                    match = false;
                    break;
                }
            }
            if (match) {
                result.add(data);
            }
        }

        sortData(result, tableKey.get(tableId));
        return result;
    }

    // 对主键升序排序
    private void sortData(List<int[]> result, String key) {
        result.sort((o1, o2) -> {
            char[] charArray = key.toCharArray();
            for (char c : charArray) {
                int index = c - 'a';
                if (o1[index] != o2[index]) {
                    return o1[index] - o2[index];
                }
            }
            return 0;
        });
    }
}
